﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net.Mail;
using System.Threading;
using System.Net.Configuration;
using System.Configuration;
using System.IO;

/// <summary>
/// Summary description for SendEmail
/// </summary>
public class SendEmailProviders
{
    public enum RoleSendEmail { User,Admin}
    public enum EmailType { UserContact,AdminContact,UserInviteFriends}
    public static string InvailableEmail(string emailList, ref List<string> AvailableEmail)
    {
        StringBuilder errors = new StringBuilder();
        string[] emails = emailList.Trim().Split(';');
        foreach (string item in emails)
        {
            if (!ValidationEmail.IsEmail(item.Trim()))
            {
                errors.AppendFormat("{0}; ", item);
            }
            else
                AvailableEmail.Add(item);
        }

        return errors.ToString();
    }

    public static string SendEmail(string fromEmail, string emailTitle, List<string> availableEmailsTo, string subject, string body, bool isHtml, bool isSSL)
    {
        StringBuilder ResultSendEmail = new StringBuilder();

        SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(fromEmail, emailTitle);
            foreach (string to in availableEmailsTo)
            {
                try
                {
                    mail.To.Add(to);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = isHtml;
                    SmtpClient client = new SmtpClient(cfg.Network.Host);
                    if (cfg.Network.Host.StartsWith("smtp.mail.yahoo"))
                    {
                        client.Port = 25;
                        client.EnableSsl = false;
                    }
                    else
                    {
                        client.Port = cfg.Network.Port;
                        client.EnableSsl = true;
                    }

                    client.Credentials = new System.Net.NetworkCredential(cfg.Network.UserName, cfg.Network.Password);
                    client.Send(mail);
                    ResultSendEmail.AppendFormat("Gửi đến: {0} -  Lúc:{1}  - Trạng thái: {2}<br/>", to, string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now), "successful.");
                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    ResultSendEmail.AppendFormat("Gửi đến: {0} -  Lúc:{1}  - Trạng thái: {2}<br/>", to, string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now), ex.Message);
                }

            }

        }

        return ResultSendEmail.ToString();

    }

    public static StringBuilder CheckError(RoleSendEmail role, string emailTitle, string hoTen, string fromEmail, string emailTo, string emailSubject, string emailContent)
    {
        StringBuilder result = new StringBuilder();       
        List<string> availableEmails = new List<string>();
        string errorEmails = InvailableEmail(emailTo, ref availableEmails);
        if (emailTo!=null && emailTo == "")
        {
            result.AppendFormat("{0}<br/>", " Email được yêu cầu.");
        }

        if (fromEmail == "")
        {
            result.AppendFormat("{0}<br/>", " Email được yêu cầu.");
        }


        if (emailSubject != null && emailSubject == "")
        {
            result.AppendFormat("{0}<br/>", "Tiêu đề email được yêu cầu.");
        }
        else if (emailSubject != null && emailSubject.Length < 6)
        {
            result.AppendFormat("{0}<br/>", "Tiêu đề phải từ 6 kí tự trở lên.");
        }

        if (emailContent == "")
        {
            result.AppendFormat("{0}<br/>", "Nội dung được yêu cầu");
        }
        else if (emailContent.Length < 6)
        {
            result.AppendFormat("{0}<br/>", "Nội dung phải từ 6 kí tự trở lên.");
        }
        return result;
    }
    public static StringBuilder Send(RoleSendEmail role, string emailTitle, string hoTen, string fromEmail, string emailTo, string emailSubject, string emailContent, string emailTemplate)
    {
        StringBuilder result = new StringBuilder();
        List<string> availableEmails = new List<string>();
        string errorEmails = InvailableEmail(emailTo, ref availableEmails);
        result = CheckError(role, emailTitle, hoTen, fromEmail, emailTo, emailSubject, emailContent);

        if (result.ToString() == "")
        {

            if (errorEmails == "")
            {                
                StreamReader sr = new StreamReader(emailTemplate);
                sr = File.OpenText(emailTemplate);
                string content = sr.ReadToEnd();
                content = content.Replace("[From]", fromEmail);
                content = content.Replace("[To]", emailTo);
                content = content.Replace("[Content]", emailContent);
                content = content.Replace("[DateTime]", string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now));
                if (role == RoleSendEmail.User)
                    content = content.Replace("[FullName]", hoTen);
                try
                {
                    result.AppendFormat("<div class=\"MessageSuccess\">{0}</div>", SendEmail(fromEmail,emailTitle, availableEmails, emailSubject.Trim(), content, true, false));

                }

                catch (Exception ex)
                {

                    result.AppendFormat("<div class=\"MessageError\">{0}</div>",ex.Message);

                }
            }
            else
            {
                result.AppendFormat("<div class=\"MessageError\">Những email không hợp lệ:{0} </div>",errorEmails);
            }
        }
        else
        {
            result.AppendFormat("<div class=\"MessageError\">{0}</div>",result.ToString());
        }

        return result;
    }



    public static StringBuilder SendInviteFriends(RoleSendEmail role, TaiLieu tailieu, string emailTitle, string hoTen, string fromEmail, string emailTo, string emailSubject,string emailTemplate)
    {
        StringBuilder result = new StringBuilder();
        List<string> availableEmails = new List<string>();
        string errorEmails = InvailableEmail(emailTo, ref availableEmails);
        result = CheckError(role, emailTitle, hoTen, fromEmail, emailTo, emailSubject, "Cai nay khong can kiem tra noi dung");

        if (result.ToString() == "")
        {

            if (errorEmails == "")
            {
                StreamReader sr = new StreamReader(emailTemplate);
                sr = File.OpenText(emailTemplate);
                string content = sr.ReadToEnd();
                if (tailieu != null) { 
                    content = content.Replace("[LinkProductImage]",tailieu.ProductPhotoURL);
                    content = content.Replace("[ProductID]", tailieu.ProductID.ToString());
                    content = content.Replace("[Title]", tailieu.ProductName);
                    content = content.Replace("[Price]", tailieu.ProductPrice.ToString());
                    content = content.Replace("[CategoryId]", tailieu.CatID.ToString());
                    content = content.Replace("[Category]", tailieu.DanhMuc.CatName);
                    content = content.Replace("[View]", tailieu.NumsView.ToString());
                    content = content.Replace("[Buy]", tailieu.NumsBuy.ToString());
                    content = content.Replace("[Content]", tailieu.ProductDescription);

                }
                content = content.Replace("[From]", fromEmail);
                content = content.Replace("[To]", emailTo);               
                content = content.Replace("[DateTime]", string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now));
                if (role == RoleSendEmail.User)
                    content = content.Replace("[FullName]", hoTen);
                try
                {
                    result.AppendFormat("<div class=\"MessageSuccess\">{0}</div>", SendEmail(fromEmail, emailTitle, availableEmails, emailSubject.Trim(), content, true, false));

                }

                catch (Exception ex)
                {

                    result.AppendFormat("<div class=\"MessageError\">{0}</div>", ex.Message);

                }
            }
            else
            {
                result.AppendFormat("<div class=\"MessageError\">Những email không hợp lệ:{0} </div>", errorEmails);
            }
        }
        else
        {
            result.AppendFormat("<div class=\"MessageError\">{0}</div>", result.ToString());
        }

        return result;
    }

}